package org.qiuqiu.backcontroller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.qiuqiu.service.impl.UserServiceImpl;
import org.qiuqiu.vo.PaginationVO;
import org.qiuqiu.vo.User;
import org.qiuqiu.vo.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/***
 * 
 * @author wangsongmao 2015年1月30日 下午2:48:22
 */
@Controller
@RequestMapping(value = "/userback")
public class UserBackController {

	@Autowired
	private UserServiceImpl userServiceImpl;
	// 用来构建JsonGenerator对象
	private ObjectMapper objectMapper = new ObjectMapper();
	// 用来创建json数据
	private JsonGenerator jsonGenerator = null;

	@RequestMapping(value = "/userList", method = RequestMethod.POST)
	public void getAllUser(
			@RequestParam(required = false, value = "key") String key,
			HttpServletResponse rs,
			HttpServletRequest re,
			@RequestParam(required = false, value = "pageIndex") int pageIndex,
			@RequestParam(required = false, value = "pageSize") int pageSize,
			@RequestParam(required = false, value = "sortField") String sortField,
			@RequestParam(required = false, value = "sortOrder") String sortOrder)
			throws Exception {
		List<User> userList = null;
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm")
				.create();
		PaginationVO page = new PaginationVO();
		page.setPageStart(pageIndex * pageSize);
		page.setPageIndex(pageIndex);
		page.setPageSize(pageSize);
		User po = new User();
		UserExample poe = new UserExample();
		if (key != null) {
			po.setUsername(key);
			poe.createCriteria().andUsernameLike("%" + key + "%");
		}
		page.setSortField(sortField);
		page.setSortOrder(sortOrder);
		userList = userServiceImpl.selectPageByAll(page, po);
		int total = userServiceImpl.countByExample(poe);
		System.out.println("" + userList);
		page.setList(userList);
		page.setTotalField(total);
		System.out.println(page);
		rs.setContentType("application/json; charset=utf-8");
		PrintWriter out = rs.getWriter();
		out.write(gson.toJson(page));
		out.flush();
		out.close();

		/*
		 * jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
		 * rs.getOutputStream()); jsonGenerator.writeObject(page);
		 */

	}

	@RequestMapping(value = "/userback")
	public String back() {
		return "userback";

	}

	/*
	 * @RequestMapping(value = "/mainBack") public String mainBack() { return
	 * "mainBack";
	 * 
	 * }
	 */

	@RequestMapping(value = "/postInformation")
	public String postInformation() {
		return "postInformation";

	}
	@RequestMapping(value = "/mainBack")
	public String mainBack() {
		return "mainBack";

	}
    @ResponseBody
	@RequestMapping(value = "/statusChanges")
	public Map<String,Object> statusChangs(@RequestParam("id") int id,@RequestParam("status")int status ,HttpServletResponse rs) {
		System.out.println("id=="+id+"  status=="+status);
		User user=null; //new User();
		Gson gson=new Gson();
		 PrintWriter out=null;
		 String code="";
		 String msg="";
		
		 Map<String, Object> map=new HashMap<String, Object>();
		 try {	
			
		   user=userServiceImpl.selectByPrimaryKey(id);
		 System.out.println(user);
			if (status==0) {
				 user.setStatus(1);
			}if (status==1) {
				user.setStatus(0);
			}
		    userServiceImpl.updateByPrimaryKey(user);
		
		 
		
		
			
		  
				
			} catch (Exception e) {
				code="1001";
				msg="失败了吗！";
			}finally{
			
				 map.put("code", code);
				 map.put("msg", msg);
				 return map;
			}
		
	}
	@RequestMapping(value = "/statusChange")
	public void statusChang(@RequestParam("id") int id,@RequestParam("userstatus")int userstatus ,HttpServletResponse rs) {
		System.out.println("id=="+id+"  status=="+userstatus);
		User user=new User();
		Gson gson=new Gson();	
		Map<String, Object> map=new HashMap<String, Object>();
		 user=userServiceImpl.selectByPrimaryKey(id);
		 System.out.println(user);
			if (userstatus==0) {
				 user.setUserstatus(1);
			}if (userstatus==1) {
				user.setUserstatus(2);
			}if (userstatus==2) {
				user.setUserstatus(0);
			}
		 userServiceImpl.updateByPrimaryKey(user);
		 String code="0101";
		 String msg="修改成功";
		 map.put("code", code);
		 map.put("msg", msg);
		 rs.setContentType("application/json; charset=utf-8");
			try {
				PrintWriter out = rs.getWriter();
				out.write(gson.toJson(map));
				out.flush();
				out.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}

	@RequestMapping(value = "/add")
	public void add(@RequestParam("data") String data, HttpServletRequest rq,
			HttpServletResponse rs) {
		System.out.println("data=" + data);
		try {
			User user = objectMapper.readValue(data, User[].class)[0];
			System.out.println("_(_++()_+" + user);
			int flag = userServiceImpl.insert(user);
			rs.setCharacterEncoding("utf-8");
			rs.setContentType("text/html;charset=utf-8");
			jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(
					rs.getOutputStream());
			jsonGenerator.writeObject(flag);
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/*
	 * @RequestMapping(value = "/save", method = RequestMethod.POST) public void
	 * saveData(@RequestParam("data") String data, HttpServletRequest rq,
	 * HttpServletResponse rs) { PostExample post = new PostExample(); //
	 * JSONObject json=new JSONObject(); Post article = new Post();
	 * System.out.println("____" + data); try { JsonParser jParser =
	 * objectMapper.getJsonFactory() .createJsonParser(data); //
	 * System.out.println(sp.getDoubleValue()); if (jParser.nextToken() !=
	 * JsonToken.END_OBJECT) {
	 * 
	 * while (jParser.nextToken() != JsonToken.END_OBJECT) {
	 * 
	 * String fieldname = jParser.getCurrentName();
	 * 
	 * if ("postid".equals(fieldname)) { // 当前结点为name jParser.nextToken();
	 * article.setPostid(jParser.getIntValue()); // System.out.println(); // 输出
	 * mkyong
	 * 
	 * } if ("userid".equals(fieldname)) { // 当前结点为name jParser.nextToken();
	 * 
	 * article.setUserid(jParser.getIntValue()); //
	 * System.out.println(jParser.getIntValue()); // 输出 // mkyong
	 * 
	 * } if ("postTitle".equals(fieldname)) { // 当前结点为name jParser.nextToken();
	 * article.setPostTitle(jParser.getText()); //
	 * System.out.println(jParser.getText()); // 输出 mkyong
	 * 
	 * } if ("postUsername".equals(fieldname)) { // 当前结点为name
	 * jParser.nextToken(); article.setPostUsername(jParser.getText()); //
	 * System.out.println(jParser.getText()); // 输出 mkyong
	 * 
	 * } if ("postCreatetime".equals(fieldname)) { // 当前结点为name
	 * jParser.nextToken(); String date = jParser.getText(); SimpleDateFormat
	 * sdf = new SimpleDateFormat( "yyyy-MM-dd kk:mm:ss.SSS");
	 * 
	 * try { System.out.println("riqi===" + sdf.parse(date));
	 * article.setPostCreatetime(sdf.parse(date)); } catch (ParseException e) {
	 * // TODO Auto-generated catch block e.printStackTrace(); } //
	 * System.out.println(jParser.getText()); // 输出 mkyong
	 * 
	 * } if ("postContent".equals(fieldname)) { // 当前结点为name
	 * jParser.nextToken(); article.setPostContent(jParser.getText()); //
	 * System.out.println(jParser.getText()); // 输出 mkyong
	 * 
	 * } if ("postRead".equals(fieldname)) { // 当前结点为name jParser.nextToken();
	 * article.setPostRead(jParser.getIntValue());
	 * 
	 * } if ("postResponse".equals(fieldname)) { // 当前结点为name
	 * jParser.nextToken(); article.setPostResponse(jParser.getIntValue());
	 * 
	 * } } System.out.println("+================" + article); int flag =
	 * postServiceImpl.updateByPrimaryKeySelective(article);
	 * System.out.println("flag==" + flag); rs.setCharacterEncoding("utf-8");
	 * rs.setContentType("text/html;charset=utf-8"); jsonGenerator =
	 * objectMapper.getJsonFactory() .createJsonGenerator(rs.getOutputStream());
	 * jsonGenerator.writeObject(flag);
	 * 
	 * } } catch (JsonParseException e) { e.printStackTrace(); } catch
	 * (IOException e) { e.printStackTrace(); }
	 * 
	 * }
	 * 
	 * @RequestMapping(value = "/query", method = RequestMethod.POST) public
	 * void query(@RequestParam("key") String key, HttpServletResponse rs)
	 * throws Exception { System.out.println("key=" + key); List<Post>
	 * articlelist = null;
	 * 
	 * PaginationVO page = new PaginationVO(); PostExample example = new
	 * PostExample(); example.createCriteria().andPostUsernameLike(key);
	 * articlelist = postServiceImpl.selectByExample(example);
	 * System.out.println("^^^^^^^%%%%^^^^" + articlelist);
	 * page.setList(articlelist); page.setTotalField(articlelist.size());
	 * rs.setCharacterEncoding("utf-8");
	 * rs.setContentType("text/html;charset=utf-8"); jsonGenerator =
	 * objectMapper.getJsonFactory().createJsonGenerator( rs.getOutputStream());
	 * jsonGenerator.writeObject(page);
	 * 
	 * }
	 * 
	 * @RequestMapping(value = "/delete") public void
	 * deletedata(@RequestParam("id") String id, HttpServletResponse rs) {
	 * String[] arry = id.split(","); ArrayList<Integer> arryList = new
	 * ArrayList<Integer>(); for (int i = 0; i < arry.length; i++) {
	 * arryList.add(Integer.parseInt(arry[i])); }
	 * System.out.println("+++++++++++++++++++++++" + arryList); PostExample
	 * example = new PostExample();
	 * example.createCriteria().andPostidIn(arryList); int flag =
	 * postServiceImpl.deleteByExample(example);
	 * rs.setCharacterEncoding("utf-8");
	 * rs.setContentType("text/html;charset=utf-8"); try { jsonGenerator =
	 * objectMapper.getJsonFactory().createJsonGenerator( rs.getOutputStream());
	 * jsonGenerator.writeObject(flag); } catch (JsonProcessingException e) { //
	 * TODO Auto-generated catch block e.printStackTrace(); } catch (IOException
	 * e) { // TODO Auto-generated catch block e.printStackTrace(); } }
	 * 
	 * @RequestMapping(value="/findById") public void
	 * findById(@RequestParam("id") int id,HttpServletResponse rs){ Post
	 * post=new Post(); post= postServiceImpl.selectByPrimaryKey(id);
	 * System.out.println("--findById----"+post); Gson gson=new
	 * GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
	 * rs.setCharacterEncoding("utf-8");
	 * rs.setContentType("text/html;charset=utf-8"); try { PrintWriter out =
	 * rs.getWriter(); out.write( gson.toJson(post)); out.flush(); out.close();
	 * } catch (JsonProcessingException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated
	 * catch block e.printStackTrace(); } }
	 */
}
